package com.lab.controller;

import com.lab.pojo.Operator;
import com.lab.pojo.Student;
import com.lab.pojo.Teacher;
import com.lab.service.OperatorService;
import com.lab.service.StudentService;
import com.lab.service.TeacherService;
import com.lab.util.Md5Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    @Resource
    TeacherService teacherService;
    @Resource
    StudentService studentService;
    @Resource
    OperatorService operatorService;
    @PostMapping("/user/login")
    public String login(HttpServletRequest request, HttpSession session, Map<String,Object> map) {
        String role = request.getParameter("role");
        String password = Md5Util.encodeByMd5(request.getParameter("password"));
        String inputStr = request.getParameter("verify_input");
        boolean verifyCode = Picverifyaction.checkVerify(inputStr, session);
        if (role.equals("2")) {
            Long tid = Long.parseLong(request.getParameter("id"));
            Teacher t = teacherService.findTeacher(tid);
            if (t!=null&&password.equals(t.getPassword()) && verifyCode) {
                session.setAttribute("user", t);
                session.setAttribute("role", "教师");
                return "redirect:/index.html";
            }else{
                map.put("msg", "用户名或密码错误");
                return "redirect:/login.html";
            }
        }else if (role.equals("1")) {
            Long sid = Long.parseLong(request.getParameter("id"));
            Student s = studentService.findStudent(sid);
            if (s!=null&&password.equals(s.getPassword()) && verifyCode) {
                session.setAttribute("user", s);
                session.setAttribute("role", "学生");
                return "redirect:/index.html";
            }else{
                map.put("msg", "用户名或密码错误");
                return "redirect:/login.html";
            }
        }else  {
            String usename = request.getParameter("id");
            Operator operator = operatorService.findOperator(usename);
            if (operator!=null&&password.equals(operator.getPassword()) && verifyCode) {
                session.setAttribute("user", operator);
                session.setAttribute("role", operator.getRole());
                return "redirect:/index.html";
            } else{
                map.put("msg", "用户名或密码错误");
                return "redirect:/login.html";
            }
        }
    }
}
